<template>
  <ContentWrap v-loading="formLoading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基础信息" name="info">
        <InfoForm
          ref="infoRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="商品规格" name="sku">
        <SkuForm
          ref="skuRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>

      <el-tab-pane label="商品权限" name="permission">
        <PermissionForm
          ref="permissionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
          :memberLevelList="memberLevelList"
          :paidMemberLevelList="paidMemberLevelList"
          :tagsList="tagsList"
        />
      </el-tab-pane>
      <el-tab-pane label="营销设置" name="promotion">
        <PromotionForm
          ref="promotionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
          :memberLevelList="memberLevelList"
          :paidMemberLevelList="paidMemberLevelList"
          :tagsList="tagsList"
        />
      </el-tab-pane>
      <el-tab-pane label="会员折扣" name="vipDiscounts">
        <VipDiscountsForm
          ref="vipDiscountsRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
          :memberLevelList="memberLevelList"
          :paidMemberLevelList="paidMemberLevelList"
          :tagsList="tagsList"
        />
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="description">
        <DescriptionForm
          ref="descriptionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <!-- <el-tab-pane label="佣金设置" name="brokerage">
        <BrokerageForm
          ref="brokerageRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane> -->
      <!-- <el-tab-pane label="其它设置" name="other">
        <OtherForm
          ref="otherRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane> -->
      <!-- <el-tab-pane label="商品协议" name="protocol">
        <ProtocolForm
          ref="protocolRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane> -->
    </el-tabs>
    <el-form>
      <el-form-item>
        <div class="flex justify-center w-full">
          <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
            {{ activeName == 'info' ? '下一步' : '保存' }}
          </el-button>
          <el-button @click="close">返回</el-button>
        </div>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/mall/product/spu'
import SkuForm from './SkuForm.vue'
import InfoForm from '@/views/mall/product/spu/form/InfoForm.vue'
import DescriptionForm from '@/views/mall/product/spu/form/DescriptionForm.vue'
import PermissionForm from '@/views/mall/product/spu/form/PermissionForm.vue'
import PromotionForm from '@/views/mall/product/spu/form/PromotionForm.vue'
import VipDiscountsForm from '@/views/mall/product/spu/form/VipDiscountsForm.vue'
// import ProtocolForm from '@/views/mall/product/spu/form/ProtocolForm.vue'
// import OtherForm from '@/views/mall/product/spu/form/OtherForm.vue'

// import BrokerageForm from '@/views/mall/product/spu/form/BrokerageForm.vue'
import { convertToInteger, floatToFixed2, formatToFraction, generateNumericUUID } from '@/utils'

defineOptions({ name: 'ProductSpuActivityAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const infoRef = ref() // 商品信息 Ref
const skuRef = ref() // 商品规格 Ref
const descriptionRef = ref() // 商品详情 Ref
const permissionRef = ref() //商品权限 Ref
const promotionRef = ref() //营销设置 Ref
const vipDiscountsRef = ref() //会员折扣 Ref
// const protocolRef = ref() //商品协议 Ref
// const brokerageRef = ref() //佣金设置
// const otherRef = ref() // 其他设置 Ref

// SPU 表单数据
const formData = ref<ProductSpuApi.Spu>({
  spuType: 3,
  spuId: undefined,
  salesChannel: [], //销售渠道
  brandId: undefined, // 商品品牌
  spuName: '', //商品名称
  titleName: '', // 商品标题(商城)
  subTitleName: '', //商品副标题
  sort: 0, // 商品排序 接口传参
  keyword: '', // 关键字
  introduction: '', // 商品简介
  spuTags: '', //商品标签
  spuColor: '#ff0000', //商品标签颜色
  picUrl: '', // 商品封面图
  imgOblongUrl: '', // 商品主图2, 长方形
  imgScale: 0, // 图片视频比例  1:1、3:4、4:3、16:9
  sliderPicUrls: [], // 商品轮播图
  isVideo: false, //是否有视频文件
  videoImg: '', //视频封面
  videoUrl: '', //视频链接
  videoAutoplay: false, //自动播放
  videoMuteplay: false, //禁音播放
  categoryId: undefined, // 商品分类编号
  salesOnlineChannel: [], // 线上商品销售渠道
  deliveryTypes: [], // 配送方式
  freightSet: 2, //运费设置 1固定运费 2运费模板
  freight: 0, //固定运费
  deliveryTemplateId: undefined, //运费模版id
  productUp: 0, //商品上架类型
  productUpTime: '', //商品上架时间
  productDown: 0, //商品下架类型
  productDownTime: '', // 商品下架时间
  tenantNumType: 1, //销售门店
  authorizedTenant: [], //销售门店
  authorizedMallTenant: [], //销售商城
  tenantServiceNumType: 1, //服务门店类型
  authorizedServiceTenant: [], //服务门店
  specType: true,
  subCommissionType: false, // 分销类型
  subCommissionEnable: false, //分销开关
  virtualSalesCount: 0, //线下销量
  skus: [
    // {
    //   price: undefined, // 商品价格
    //   lowPrice: 0, //最低价
    //   marketPrice: 0, // 划线价
    //   costPrice: 0, // 成本价
    //   activityStartTime: '', //活动商品开始时间
    //   activityEndTime: '', //活动商品结束时间
    //   isUpdated: undefined, //N选N活动是否允许修改
    //   number: undefined, //活动N类
    //   deductionScopes: [], //N选N活动 活动抵扣设置类型
    //   generalProductList: [], //N选N活动关联商品列表
    //   skuType: 34, //商品属性
    //   skuId: generateNumericUUID(), //商品 SKU 编号
    //   stock: undefined,
    //   firstBrokeragePrice: 0, // 一级分销的佣金
    //   secondBrokeragePrice: 0, // 二级分销的佣金
    //   firstBrokeragePercent: 0, // 一级分销的佣金 比例
    //   secondBrokeragePercent: 0, // 二级分销的佣金 比例
    //   firstBrokerageType: 2, // 一级分销的佣金类型
    //   secondBrokerageType: 2, // 二级分销的佣金类型
    //   spuData: {
    //     skus: []
    //   }
    // }
  ],
  description: '', // 商品详情
  /**浏览权限 */
  browseAuthority: [0], //浏览权限 0 不限制 1 指定会员等级可见 2 指定付费会员等级可见 4指定标签组可见
  browseMember: undefined, //浏览权限 会员
  browsePaidMember: undefined, //浏览权限 付费会员
  browseTags: undefined, //浏览权限 标签组
  /** 购买权限 */
  buyAuthority: [0], //购买权限
  buyMember: undefined, //购买权限 会员
  buyPaidMember: undefined, //购买权限 付费会员
  buyTags: undefined, //购买权限 标签组
  /** 商品限购 */
  quotaAuthority: 0, //商品限购
  singleQuotaMini: undefined, //商品限购 单次最少
  singleQuotaMax: undefined, //商品限购 单次最多
  permanentQuota: undefined, //商品限购 永久限购
  /** 营销设置 */
  memberPointsGain: 0, //会员积分获取
  memberPointsGainEntry: {}, //会员积分获取单独设置
  paidmemberPointsGain: 0, //付费会员积分获取
  paidmemberPointsGainEntry: {}, //付费会员积分获取单独设置,
  memberWalletRule: 0, //会员余额抵扣
  memberWalletRuleEntry: {}, //会员抵扣单独设置,
  paidmemberWalletRule: 0, //付费会员余额抵扣
  paidmemberWalletRuleEntry: {}, //付费会员余额抵扣单独设置
  /** 会员折扣设置 */
  memberDiscount: 0, //会员折扣
  memberDiscountEntry: {}, //会员折扣单独设置
  /** 付费会员折扣设置 */
  paidmemberDiscount: 0, //付费会员折扣设置
  paidmemberDiscountEntry: {} //付费会员折扣单独设置
})
/** 获取会员等级 */
const memberLevelList = ref()
import * as LevelApi from '@/api/member/level'
const getMemberLevelList = async () => {
  memberLevelList.value = await LevelApi.getSimpleLevelList()
}
/** 获取付费会员等级 */
const paidMemberLevelList = ref()
const getPaidMemberLevelList = async () => {
  let params = {
    spuType: 5
  }
  paidMemberLevelList.value = await ProductSpuApi.getSpuSimpleList(params)
}
/** 获取标签组 */
const tagsList = ref()
import * as TagApi from '@/api/member/tag'

const getTagslList = async () => {
  tagsList.value = await TagApi.getSimpleTagList()
}
/** 获得详情 */
const getDetail = async () => {
  if ('ProductSpuActivityDetail' === name) {
    isDetail.value = true
  }
  const spuId = params.spuId as unknown as number
  if (spuId) {
    formLoading.value = true
    try {
      const res = (await ProductSpuApi.getSpu(spuId)) as ProductSpuApi.Spu
      console.log(res)

      if (isDetail.value) {
        res.freight = floatToFixed2(res.freight)
      } else {
        // 固定运费回显价格分转元
        res.freight = formatToFraction(res.freight)
      }
      res.skus?.forEach((item) => {
        if (isDetail.value) {
          item.price = floatToFixed2(item.price)
          item.lowPrice = floatToFixed2(item.lowPrice)
          item.marketPrice = floatToFixed2(item.marketPrice)

          item.firstBrokeragePrice = floatToFixed2(item.firstBrokeragePrice)
          item.secondBrokeragePrice = floatToFixed2(item.secondBrokeragePrice)
        } else {
          // 回显价格分转元
          item.price = formatToFraction(item.price)
          item.lowPrice = formatToFraction(item.lowPrice)
          item.marketPrice = formatToFraction(item.marketPrice)
          item.firstBrokeragePrice = formatToFraction(item.firstBrokeragePrice)
          item.secondBrokeragePrice = formatToFraction(item.secondBrokeragePrice)
        }
        item.spuData = {
          skus: []
        }
      })
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交按钮 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 校验各表单
    await unref(infoRef)?.validate()
    // 在规格项界面触发保存操作
    if (activeName.value == 'info') {
      activeName.value = 'sku'
      return
    }
    await unref(skuRef)?.validate()
    await unref(descriptionRef)?.validate()
    await unref(permissionRef)?.validate()
    await unref(promotionRef)?.validate()
    await unref(vipDiscountsRef)?.validate()
    // await unref(brokerageRef)?.validate()
    // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
    const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu
    // 固定运费价格元转分
    deepCopyFormData.freight = convertToInteger(deepCopyFormData.freight)

    deepCopyFormData.skus!.forEach((item) => {
      // 给sku name赋值
      item.spuName = deepCopyFormData.spuName
      // sku相关价格元转分
      item.price = convertToInteger(item.price)
      item.lowPrice = convertToInteger(item.lowPrice)
      item.marketPrice = convertToInteger(item.marketPrice)
      item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice)
      item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice)
      delete item.spuData
    })
    // 处理轮播图列表
    const newSliderPicUrls: any[] = []
    deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
      // 如果是前端选的图
      typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
    })
    deepCopyFormData.sliderPicUrls = newSliderPicUrls
    // 校验都通过后提交表单
    const data = deepCopyFormData as ProductSpuApi.Spu
    const spuId = params.spuId as unknown as number
    if (!spuId) {
      await ProductSpuApi.createSpu(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductSpuApi.updateSpu(data)
      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ProductSpuActivity' })
}

/** 初始化 */
onMounted(async () => {
  await getMemberLevelList()
  await getPaidMemberLevelList()
  await getTagslList()
  await getDetail()
})
</script>
